<template>
  <div v-loading="loading">
    <el-table :data="plateContentList" style="width: 100%" stripe @sort-change="handleSortChange">
      <el-table-column prop="sSectname" align="center" min-width="90">
        <template #header>
          <el-tooltip
            popper-class="tooltip-class-blue"
            content="可点击查看单一概念板块行情"
            placement="top"
            effect="light"
          >
            <span class="cursor-pointer" ref="clickHeadRef" v-click-outside="clickHeaderName">
              概念板块
            </span>
          </el-tooltip>

          <el-popover
            ref="popoverRef"
            :virtual-ref="clickHeadRef"
            v-model:visible="popoverNameVisible"
            trigger="click"
            virtual-triggering
            :width="300"
            persistent
          >
            <template #default>
              <el-input
                v-model="searchText"
                placeholder="搜索概念板块"
                class="mb-2"
                @input="handleInputSearch"
              >
              </el-input>

              <el-scrollbar max-height="300px" v-if="filteredSectors.length > 0">
                <el-checkbox-group v-model="selectedSectors">
                  <div v-for="sector in filteredSectors" :key="sector.value" class="sector-item">
                    <el-checkbox :label="sector.value">
                      {{ sector.label }}
                    </el-checkbox>
                  </div>
                </el-checkbox-group>
              </el-scrollbar>
              <div v-if="filteredSectors.length > 0">
                <el-button size="mini" @click="handleReset">重置</el-button>
                <el-button type="primary" size="mini" @click="handleConfirm"> 确认 </el-button>
              </div>
              <div v-else class="flex justify-center">
                <span>暂无数据</span>
              </div>
            </template>
          </el-popover>
        </template>
        <template #default="scope">
          <span class="text-[#2468f2] cursor-pointer" @click="queryByName(scope.row)">
            {{ scope?.row?.sSectname }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="amountMa20"
        label="20个交易日日均成交额(亿元)"
        align="center"
        min-width="220"
        sortable="custom"
      >
        <template #default="scope">
          {{ formatAmountMa20(scope?.row?.amountMa20) }}
        </template>
        <template #header="{ column }">
          <div class="flex items-center">
            <span>{{ column.label }}</span>
            <div>
              <!-- 筛选图标 -->
              <el-popover
                placement="bottom"
                :width="340"
                trigger="click"
                v-model:visible="popoverVisible"
              >
                <template #reference>
                  <Icon
                    icon="material-symbols:filter-alt-outline"
                    width="20"
                    height="20"
                    class="filter-icon"
                    @click.stop="handleFilterClick"
                  />
                </template>
                <div class="filter-content">
                  <div class="filter-inputs">
                    <el-input placeholder="最小值(单位:亿元)" size="mini" v-model="minAmountMa20" />
                    <span class="separator">-</span>
                    <el-input placeholder="最大值(单位:亿元)" size="mini" v-model="maxAmountMa20" />
                  </div>
                  <div class="filter-buttons">
                    <el-button size="mini" @click="handleFilterReset">重置</el-button>
                    <el-button type="primary" size="mini" @click="handleFilterConfirm"
                      >确认</el-button
                    >
                  </div>
                </div>
              </el-popover>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="return5d"
        label="近5个交易日收益"
        align="center"
        min-width="150"
        sortable="custom"
      >
        <template #default="scope">
          {{ fixed2(scope?.row?.return5d) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="return10d"
        label="近10个交易日收益"
        align="center"
        min-width="150"
        sortable="custom"
      >
        <template #default="scope">
          {{ fixed2(scope?.row?.return10d) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="return1m"
        label="近1个月收益"
        align="center"
        min-width="110"
        sortable="custom"
      >
        <template #default="scope">
          {{ fixed2(scope?.row?.return1m) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="return3m"
        label="近3个月收益"
        align="center"
        min-width="110"
        sortable="custom"
      >
        <template #default="scope">
          {{ fixed2(scope?.row?.return3m) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="return6m"
        label="近6个月收益"
        align="center"
        min-width="110"
        sortable="custom"
      >
        <template #default="scope">
          {{ fixed2(scope?.row?.return6m) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="return1y"
        label="近1年收益"
        align="center"
        min-width="110"
        sortable="custom"
      >
        <template #default="scope">
          {{ fixed2(scope?.row?.return1y) }}
        </template>
      </el-table-column>
    </el-table>

    <div style="display: flex; justify-content: end; margin-top: 16px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, defineEmits, unref, computed, watch } from 'vue'
import { ClickOutside as vClickOutside } from 'element-plus'
import { getW1055047, getW1055055 } from '@/api/etfpegging.js'
import { ElMessage } from 'element-plus'
const plateContentList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(true)
import { Icon } from '@iconify/vue'
const popoverVisible = ref(false)
const popoverNameVisible = ref(false)

//20交易日筛选
const minAmountMa20 = ref('')
const maxAmountMa20 = ref('')

const handleFilterConfirm = () => {
  const params = {
    minAmountMa20: minAmountMa20.value ? parseFloat(minAmountMa20.value) * 100000000 : undefined,
    maxAmountMa20: maxAmountMa20.value ? parseFloat(maxAmountMa20.value) * 100000000 : undefined,
  }
  // 验证数值有效性
  if (params.minAmountMa20 && isNaN(params.minAmountMa20)) {
    ElMessage.warning('请输入有效的最小值')
    return
  }
  if (params.maxAmountMa20 && isNaN(params.maxAmountMa20)) {
    ElMessage.warning('请输入有效的最大值')
    return
  }
  currentPage.value = 1
  getW1055047Data()
  popoverVisible.value = false
}

const handleFilterReset = () => {
  minAmountMa20.value = ''
  maxAmountMa20.value = ''
  currentPage.value = 1
  popoverVisible.value = false
  getW1055047Data()
}
// 点击处理
const handleFilterClick = (e: Event) => {
  minAmountMa20.value = ''
  maxAmountMa20.value = ''
  e.preventDefault()
  e.stopPropagation()
}
const clickHeadRef = ref()
const popoverRef = ref()
const clickHeaderName = () => {
  unref(popoverRef).popperRef?.delayHide?.()
}

//版块搜索
let searchTimer: number
const handleInputSearch = () => {
  clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    const params = {
      searchField: 'sSectname',
      searchContent: searchText.value,
      currentPage: 1,
      pageSize: 20,
      dataSource: dataSource.dataSource,
    }
    getW1055055(params).then((res: any) => {
      if (res?.data) {
        filteredSectors.value = res.data.map((item: any) => ({
          value: item.searchValue,
          label: item.searchValue,
        }))
      }
    })
  }, 300)
}
const searchText = ref('')
const selectedSectors = ref<string[]>([])
const filteredSectors = ref<Array<{ value: string; label: string }>>([])
const selectedSectNames = ref<string[]>([])

// 重置筛选
const handleReset = () => {
  selectedSectors.value = []
  selectedSectNames.value = []
  filteredSectors.value = []
  popoverNameVisible.value = false
  currentPage.value = 1
  searchText.value = ''
  getW1055047Data()
}
// 确认筛选
const handleConfirm = () => {
  // 获取选中的板块名称
  selectedSectNames.value = selectedSectors.value.map((code) => {
    const sector = filteredSectors.value.find((s) => s.value === code)
    return sector?.label || ''
  })

  currentPage.value = 1
  getW1055047Data()
  popoverNameVisible.value = false
  searchText.value = ''
}
// 定义 emit 事件
const emit = defineEmits(['clickName'])

const queryByName = (row: any) => {
  emit('clickName', { sSectcode: row.sSectcode, sSectname: row.sSectname })
}
const formatAmountMa20 = (val: any) => {
  if (!val) return '--'
  // 先进行单位转换，除以1亿（再乘以100）得到以亿元为单位的数据
  const result = (val * 100) / 100000000
  // 使用 toLocaleString 方法添加千分位分隔符，并保留两位小数
  return result.toLocaleString(undefined, {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  })
}

const fixed2 = (val: any) => {
  if (!val) return '--'
  return val.toFixed(2) + '%'
}

// 排序相关逻辑
const orderFlag = ref(0) // 默认降序
const sortField = ref('amountMa20') // 默认按板块名称排序

const handleSortChange = ({ prop, order }: { prop: string; order: string }) => {
  sortField.value = prop
  orderFlag.value = order === 'ascending' ? 1 : 0
  currentPage.value = 1 // 排序变更后重置到第一页
  getW1055047Data()
}
import { useLabelStore } from '@/stores/etfPeggingStore/labelStore'
const dataSource = useLabelStore()
watch(
  () => dataSource.dataSource,
  (newVal) => {
    selectedSectNames.value = []
    getW1055047Data()
  },
)
const getW1055047Data = () => {
  const params = {
    currentPage: currentPage.value,
    pageSize: pageSize.value,
    orderFlag: orderFlag.value, // 排序参数
    orderField: sortField.value, // 排序字段
    sSectNames: selectedSectNames.value,
    minAmountMa20: minAmountMa20.value ? parseFloat(minAmountMa20.value) * 1000000 : undefined,
    maxAmountMa20: maxAmountMa20.value ? parseFloat(maxAmountMa20.value) * 1000000 : undefined,
    dataSource: dataSource.dataSource,
  }
  getW1055047(params)
    .then((res: any) => {
      if (res && res.data.records) {
        plateContentList.value = res.data.records
        total.value = res.data.total
      }
      loading.value = false
    })
    .catch(() => {
      loading.value = false
    })
}

const handleSizeChange = (val: any) => {
  pageSize.value = val
  currentPage.value = 1
  getW1055047Data()
}

const handleCurrentChange = (val: any) => {
  currentPage.value = val
  getW1055047Data()
}

onMounted(() => {
  getW1055047Data()
})
</script>

<style scoped lang="scss">
:deep(.el-table .cell) {
  display: flex;
  align-items: center;
}

/* Popover内容样式 */
.filter-content {
  padding: 8px;
}

.filter-inputs {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.separator {
  color: #606266;
  flex-shrink: 0;
}

.filter-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style>
